package cn.com.api.service.impl;



import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiNewFindOrder;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiTmember;
import cn.com.api.mapper.ApiNewFindOrderMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.service.ApiNewFindOrderService;
import cn.com.util.*;

@Service
public class ApiNewFindOrderServiceImpl implements ApiNewFindOrderService {
	
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;

	@Autowired
	private ApiNewFindOrderMapper newFindOrderMapper;

	private static Logger logger = Logger.getLogger(ApiNewFindOrderServiceImpl.class);

	@Override
	public long queryUserMoney(String u_id) {

		ApiTmember member = apiTmemberMapper.findMemberByCid(Integer.parseInt(u_id));
		if(member == null){
			return 0;
		}
		return member.getCmoney().longValue();
	}

	public void updUserMoney(String u_id, double resMoney) {
		ApiTmember member = new ApiTmember();
		member.setCmoney(Util.getBigDecimal(resMoney+""));
		apiTmemberMapper.updateApiTmember(member);
	}


	@Override
	public Map<String, Object> orderInfo(String rid) {
		Map<String, Object> map = new HashMap<String, Object>();
		map = newFindOrderMapper.queryOrderDetail(rid);
		map.put("rid", map.get("RID"));
		map.put("user_id", map.get("USER_ID"));
		map.put("name", map.get("NAME"));
		map.put("mobile", map.get("MOBILE")== null?map.get("MOBILE"):"");
		map.put("address", map.get("ADDRESS")== null?map.get("ADDRESS"):"");
		map.put("titles", map.get("TITLES")== null?map.get("TITLES"):"");
		map.put("points", map.get("POINTS")== null?map.get("POINTS"):"");
		map.put("num", map.get("NUM"));
		map.remove("USER_ID");
		map.remove("NUM");
		map.remove("RID");
		map.remove("MOBILE");
		map.remove("TITLES");
		map.remove("POINTS");
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "返回订单详情成功");
		return map;
	}
	
	@Transactional
	@Override
	public Map<String, Object> initOrder(ApiNewFindOrder apiNewFindOrder) {
	
		Map<String, Object> map = new HashMap<String, Object>();
		int num = apiNewFindOrder.getNum();// 数量
		String discover_id = apiNewFindOrder.getDiscover_id();// 活动ID

		if(bolOrderLimit(num, discover_id)){			
//			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
//			map.put(Utils.MESSAGE, "报名人数超限！");
		}else{		
			ApiTmember member = apiTmemberMapper.findMemberByCid(Integer.parseInt(apiNewFindOrder.getUser_id()));
			if( member == null){
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "用户不存在！");
			}else{							
				newFindOrderMapper.insertOrder(apiNewFindOrder);
				newFindOrderMapper.insertOrderDetail(apiNewFindOrder);
				map.put("rid", apiNewFindOrder.getOrdernum());
				map.put("name", apiNewFindOrder.getName());
				map.put("phone", apiNewFindOrder.getMobile());
				map.put("money", apiNewFindOrder.getMoney());
				map.put("num", apiNewFindOrder.getNum());
				map.put("desc", apiNewFindOrder.getBz());
				map.put("balance", queryUserMoney(apiNewFindOrder.getUser_id()));
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "成功！");
			}
			
		}
		
		return map;
	}

	@Override
	public void sureOrderInfo(ApiNewFindOrder apiNewFindOrder) {
		// TODO 应该检查订单信息是否被篡改或者其他操作，UE暂时不明确，后续补充,目前只做订单状态的更新
		newFindOrderMapper.sureOrder(apiNewFindOrder);
	}
	


	
	
	/**
	 * 判断人数是否超限
	 * @param num
	 * @param discoverId
	 * @return
	 */
	private boolean bolOrderLimit(int num, String discoverId){

		/*String peopleLimit = 
				newFindOrderMapper.queryPersonLimit(discoverId);
		
		if(peopleLimit == null){
			return true;
		}
		int buySum = 
				newFindOrderMapper.queryNumInOrder(discoverId);
		logger.info("=========[ApiNewFindOrderServiceImpl[bolOrderLimit[peopleLimit:"+peopleLimit+",buySum:"+buySum+"]]==============");
		if(Integer.parseInt(peopleLimit) < buySum + num){
			return true;
		}*/
		return false;
	}
	
	
	@Transactional
	@Override
	public Map<String, Object> confirmOrderPay(ApiNewFindOrder apiNewFindOrder) {
		Map<String, Object> map = new HashMap<String, Object>();
		String payType = apiNewFindOrder.getPayType();
		BigDecimal sumPrice = apiNewFindOrder.getMoney();
		String u_id = apiNewFindOrder.getUser_id();

		
		if ((ApiNewFindOrder.PAY_TYPE_YY).equals(payType)) {
			double sumMoney = sumPrice.doubleValue();
			// 查询账户总金额
			double cMoney = queryUserMoney(u_id);
			// 判断金额大小写，购买金额大于账户金额，返回错误消息，购买金额小于等于账户金额，交易成功

			if (sumMoney > cMoney) {
				map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
				map.put(Utils.MESSAGE, "余额不足！");
			} else {

				// 更新账户余额		
				double resMoney = cMoney - sumMoney;// 暂时的余额
				updUserMoney(u_id, resMoney);
				newFindOrderMapper.surePay(apiNewFindOrder);
				//插入流水账
				apiNewFindOrder.setCurDate(new Date());
				apiNewFindOrder.setPay_type_desc("余额支付");
				apiNewFindOrder.setCate_type(ApiNewFindOrder.CATE_TYPE);
				apiNewFindOrder.setProcess_type(ApiNewFindOrder.PROCESS_TYPE);
				newFindOrderMapper.insertUserCashRecords(apiNewFindOrder);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "支付成功！");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "目前只支持余额支付！");
		}
		return map;
	}

	@Override
	public List<ApiT_order> getOrdersList(Map<String, Object> param) {
		// TODO Auto-generated method stub
		return newFindOrderMapper.getOrdersList(param);
	}

	
}
	
	
	
